// pages/sendneeddescribe/sendneeddescribe.js

//语音config 开始
var IM = require('../libs/IM.js');
var Config = require('../libs/config');
var Uploader = require('../libs/UploaderV5.js');
//语音config 结束
var app = getApp();
var c = require('../common.js');
var upimg = require('../upimg.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputvalue_moneytype:0,
    zz1: '../img/addimg.png',
    index:0,
    indextype:0,
    array: ['天', '小时'],
    arraytype:['日结','周结','月结','完工结算'],
    vhidden: true,
    hiddeninfo: true,
    long: null,
    action: 0,
    classaction: 'action',
    calasactionnot: 'actionnot',
    date: null,
    datend: null,
    time: '9:00',
    focustime:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //1、获取当前位置坐标
    var that=this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        var latitude = res.latitude
        var longitude = res.longitude
        that.setData({
          latitude: latitude,
          longitude: longitude,
        })
        wx.request({
          url: app.url +'address', //仅为示例，并非真实的接口地址
          data: {
            lat: latitude,
            lng: longitude
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function (res) {
            that.setData({
              addressinfo: res.data.address,
              province: res.data.province,
              city: res.data.city,
              district: res.data.district,
            })

          }
        })

      }
    })



    var myDate = new Date();
    //获取当前年
    var year = myDate.getFullYear();
    //获取当前月
    var month = myDate.getMonth() + 1;
    //获取当前日
    var date = myDate.getDate(); 
    var timedate = year + '-' + month + '-' + date;
    this.setData({ date: timedate, datend: timedate})
    this.recorder = wx.getRecorderManager();
    //音频录制完成后执行上传操作
    this.recorder.onStart((res) => {
      console.debug('start record')
    });
    this.recorder.onStop((res) => {
      console.debug('end record')
      this.uploadFile(res.tempFilePath);
    });

    var cate_id= options.cate_id;
    // var cate_id = 193;
    c.ajax(
      app.url + 'sendescript', {
        cate_id: cate_id
      },
      res => {
        this.setData({
          info: res.data,
          bottomname: res.data[0].name
        })
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //选择是哪个分类
  selectclass: function(e) {
    var index = e.currentTarget.dataset.index;
    var info = this.data.info;
    this.setData({
      action: index,
      bottomname: info[index].name
    })
  },
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  bindDateChangend: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      datend: e.detail.value
    })
  },
  bindTimeChangend: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      timend: e.detail.value
    })
  },
  simpleUpload: function(e) {
    var path = 'demand/' + new Date().getTime() + '.png';
    var that = this;
    var returninfo = upimg.simpleUpload(
      path,
      function(res) {
        console.log(res);
        that.setData({
          arrayimg: res
        })
      },
      6
    );
  },
  simpleUploadone: function (e) {
    var path = 'demand/' + new Date().getTime() + '.png';
    var that = this;
    var returninfo = upimg.simpleUpload(
      path,
      function (res) {
        console.log(res);
        that.setData({
          zz1dbs: res[0].dbs,
          zz1: res[0].imgLocation
        })
      },
      6
    );
  },
  //页面事件绑定，长按按钮的开始
  record_start: function() {
    var timedata = new Date();
    var timestring = timedata.getTime();
    this.setData({
      stime: timestring,
      hiddeninfo: false
    })
    this.recorder.start({
      format: "mp3"
    });
  },

  //页面事件绑定，长按按钮的结束
  record_end: function() {
    var longclick = this.data.longclick;
    if (longclick!=1){
       wx.showToast({
         title: '录音时间短！',
         icon:'none'
       })
      this.setData({
        hiddeninfo: true,
        
      });
      return;
    }
    var timedata = new Date();
    var timestring = timedata.getTime();
    var time = timestring - this.data.stime;
    var sint = parseInt(time / 1000);
    var mint = parseInt((time - sint * 1000) / 10);
    var long = sint * 20 + 'rpx';
    this.setData({
      longclick:0,
      sint: sint,
      mint: mint,
      long: long,
      hiddeninfo: true,
      vhidden: false,
      longtime: time
    });
    this.recorder.stop();
  },
  //长按
  simpleRecorder:function(){
   this.setData({longclick:1});
  },
  // 简单上传文件
  uploadFile(tempFilePath) {
    console.error('uploadFile', tempFilePath);
    var ntime=new Date();
    var time = ntime.getTime();
    var pathurl = '/demand/' + time+'demand';
    var that = this;
    Uploader.upload(tempFilePath, function(result) {

      if (Config.COSv4) {
        var audioUrl = result.data.data.source_url.replace("http://", "https://")
      } else {
        var audioUrl = result.Location.replace("http://", "https://")
      }

      var audioUrlnew = audioUrl.replace('uploadFile', '')
      //更新demo的数据展示
      that.setData({
        sendAudioList: audioUrlnew,
        imgurl: pathurl+'.mp3'
      })
    }, '', pathurl);
  },

  avdiov: function() {
    const innerAudioContext = wx.createInnerAudioContext()
    var path = this.data.sendAudioList;
    innerAudioContext.autoplay = true;
    innerAudioContext.src = path;
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  bindinputclick: function(e) {
    var inputvalue_time = e.detail.value;
    this.setData({
      inputvalue_time: inputvalue_time
    });
  },
  bindinputclickmoney: function (e) {
    var inputvalue_money = e.detail.value;
    this.setData({
      inputvalue_money: inputvalue_money
    });
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var inputvalue_moneytype = e.detail.value;
    this.setData({
      inputvalue_moneytype: inputvalue_moneytype
    });
  },
  bindinputTextarea: function(e) {
    var inputvalue_textarea = e.detail.value;
    this.setData({
      inputvalue_textarea: inputvalue_textarea
    });
  },
  submit: function() {
    var index = this.data.action;
    //标题
    var title = this.data.title;
    //工作时间截止时间
    var datend = this.data.datend;
    //工作时长
    var inputvalue_time = this.data.inputvalue_time;
    //工作酬薪
    var inputvalue_money = this.data.inputvalue_money;
    //工作酬薪方式
    var inputvalue_moneytype = this.data.inputvalue_moneytype;
    //结算方式
    var indextype = this.data.indextype;
    //工作地点
    var addressinfo = this.data.addressinfo;
    //工作地点经纬度
    var latitude = this.data.latitude;
    var longitude = this.data.longitude;
    //封面
    var zz1dbs = this.data.zz1dbs;



    //类别id
    var cate_id = this.data.info[index]['cate_id'];
    //听课日期
    var data = this.data.date;
    //听课时长
    var inputvalue_time = this.data.inputvalue_time;
    //描述
    var inputvalue_textarea = this.data.inputvalue_textarea;
    //图片数组 url
    var arrayimg = this.data.arrayimg;
    //语音 url
    var sendAudioList = this.data.imgurl;
    //语音时长
    var longtime = this.data.longtime;
    //用户id
    var uid = wx.getStorageSync('userInfo').user_id;
    //需求类型
    var needtype = this.data.bottomname;
    //判断
    if (typeof (inputvalue_time) =='undefined'){
        wx.showToast({
          title: '请填写听课时长',
          icon:'none'
        })
        return;
    }
    //判断
    if (typeof (inputvalue_time) == 'undefined') {
      wx.showToast({
        title: '请填写听课时长',
        icon: 'none'
      })
      return;
    }
    //判断
    if (typeof (sendAudioList) == 'undefined') {
      sendAudioList='';
    }
    //图片字符串
    var arrayimgnew = '';
    console.log(arrayimg);
    if (arrayimg) {
      for (var i = 0; i < arrayimg.length; i++) {
        arrayimgnew += arrayimg[i]['dbs'] + ',';
      }
      arrayimgnew = arrayimgnew.substring(0, arrayimgnew.length - 1);
    }
     
    c.ajax(
      app.url+'addGoodsNeed',
      { title: title, datend: datend, inputvalue_time: inputvalue_time, inputvalue_money: inputvalue_money, inputvalue_moneytype: inputvalue_moneytype, indextype: indextype, addressinfo: addressinfo, latitude: latitude, longitude: longitude, zz1dbs: zz1dbs, cate_id: cate_id, data: data, inputvalue_time: inputvalue_time, inputvalue_textarea: inputvalue_textarea, arrayimgnew: arrayimgnew, sendAudioList: sendAudioList, longtime: longtime, uid: uid, needtype: needtype},
      res=>{
        console.log(res.data);
        if (res.data){
            wx.showToast({
              title: '发布成功',
              icon: 'none',
            })
            setTimeout(function(){
              wx.switchTab({
                url: '/pages/index/index',
              })
            },1000)
        }
      }
    ) 
     

    // var param = '?index=' + index + '&cate_id=' + cate_id + '&data=' + data + '&time=' + time + '&inputvalue_time=' + inputvalue_time + '&inputvalue_textarea=' + inputvalue_textarea + '&sendAudioList=' + sendAudioList + '&arrayimg=' + arrayimgnew + '&longtime=' + longtime + '&uid=' + uid + '&needtype=' + needtype;
    // wx.navigateTo({
    //   url: '/pages/sendneedyusuan/sendneedyusuan' + param,
    // })

  },
  focusclick:function(){
    this.setData({ focustime:true})
  },
  focusclickw: function () {
    this.setData({ focustimew: true })
  },

  bindPickerChangetype: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      indextype: e.detail.value
    })
  },
  addressinfotab: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({ addressinfo: res.address, latitude: res.latitude, longitude: res.longitude });
        //选择城市区域的时候 需要覆盖之前的 省市区 province city district
        wx.request({
          url: app.url+'address', //仅为示例，并非真实的接口地址
          data: {
            lat: res.latitude,
            lng: res.longitude
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function (res) {
            that.setData({
              province: res.data.data.province,
              city: res.data.data.city,
              district: res.data.data.district,
            })

          }
        })
      }
    })
  },
  title:function(e){
    var title= e.detail.value;
    this.setData({ title: title})
  }
})